import 'dart:convert';
import 'dart:math';
import '../models/activity.dart';

/// 活动服务类
class ActivityService {
  static final ActivityService _instance = ActivityService._internal();
  factory ActivityService() => _instance;
  ActivityService._internal();

  // 模拟数据存储
  final List<Activity> _activities = [];
  final List<String> _userRegistrations = []; // 用户报名记录
  final List<String> _userFavorites = []; // 用户收藏记录

  /// 初始化模拟数据
  void initializeMockData() {
    if (_activities.isNotEmpty) return;

    final now = DateTime.now();
    _activities.addAll([
      Activity(
        id: '1',
        title: '传统剪纸艺术体验工坊',
        description: '学习传统剪纸技艺，体验非遗文化魅力。由国家级非遗传承人亲自指导，从基础技法到创意设计，让您深入了解剪纸艺术的精髓。',
        type: ActivityType.workshop,
        status: ActivityStatus.ongoing,
        startTime: now.subtract(const Duration(days: 1)),
        endTime: now.add(const Duration(days: 7)),
        location: '北京非遗文化中心',
        address: '北京市朝阳区文化街123号',
        maxParticipants: 30,
        currentParticipants: 18,
        price: 168.0,
        originalPrice: 268.0,
        images: [
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20Chinese%20paper%20cutting%20art%20workshop%20scene&image_size=landscape_4_3',
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=paper%20cutting%20tools%20and%20red%20paper&image_size=square',
        ],
        organizer: '北京非遗保护中心',
        instructor: '张师傅（国家级非遗传承人）',
        requirements: ['无需基础', '自备剪刀'],
        highlights: ['国家级传承人指导', '作品可带走', '颁发结业证书'],
        createdAt: now.subtract(const Duration(days: 10)),
        updatedAt: now.subtract(const Duration(hours: 2)),
        isFeatured: true,
        rating: 4.8,
        reviewCount: 156,
        tags: ['剪纸', '传统工艺', '体验', '非遗'],
        category: '传统工艺',
      ),
      Activity(
        id: '2',
        title: '京剧脸谱绘制艺术课',
        description: '探索京剧脸谱的奥秘，学习传统脸谱绘制技艺。了解不同脸谱的寓意和绘制方法，感受国粹艺术的博大精深。',
        type: ActivityType.course,
        status: ActivityStatus.upcoming,
        startTime: now.add(const Duration(days: 3)),
        endTime: now.add(const Duration(days: 10)),
        location: '梨园戏曲学院',
        address: '北京市西城区戏曲街88号',
        maxParticipants: 25,
        currentParticipants: 12,
        price: 288.0,
        originalPrice: 388.0,
        images: [
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=Beijing%20opera%20face%20painting%20colorful%20masks&image_size=landscape_4_3',
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20Chinese%20opera%20makeup%20brushes&image_size=square',
        ],
        organizer: '梨园戏曲学院',
        instructor: '李老师（京剧表演艺术家）',
        requirements: ['对戏曲有兴趣', '自备围裙'],
        highlights: ['专业老师指导', '了解脸谱文化', '制作个人作品'],
        createdAt: now.subtract(const Duration(days: 8)),
        updatedAt: now.subtract(const Duration(hours: 5)),
        isFeatured: true,
        rating: 4.7,
        reviewCount: 89,
        tags: ['京剧', '脸谱', '绘画', '国粹'],
        category: '戏曲艺术',
      ),
      Activity(
        id: '3',
        title: '古琴雅集音乐会',
        description: '聆听古琴悠扬琴声，感受千年古韵。邀请多位古琴名家现场演奏经典曲目，并有互动体验环节。',
        type: ActivityType.performance,
        status: ActivityStatus.upcoming,
        startTime: now.add(const Duration(days: 5)),
        endTime: now.add(const Duration(days: 5, hours: 2)),
        location: '古韵音乐厅',
        address: '北京市东城区音乐街66号',
        maxParticipants: 100,
        currentParticipants: 45,
        price: 128.0,
        originalPrice: 168.0,
        images: [
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=ancient%20Chinese%20guqin%20performance%20elegant%20setting&image_size=landscape_4_3',
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20Chinese%20guqin%20instrument&image_size=square',
        ],
        organizer: '古韵文化社',
        instructor: '王大师（古琴演奏家）',
        requirements: ['无特殊要求'],
        highlights: ['名家演奏', '经典曲目', '互动体验'],
        createdAt: now.subtract(const Duration(days: 12)),
        updatedAt: now.subtract(const Duration(hours: 1)),
        isFeatured: false,
        rating: 4.9,
        reviewCount: 234,
        tags: ['古琴', '音乐会', '传统音乐', '雅集'],
        category: '传统音乐',
      ),
      Activity(
        id: '4',
        title: '茶艺文化体验日',
        description: '品味中华茶文化，学习传统茶艺。从茶叶知识到冲泡技艺，全方位体验茶文化的博大精深。',
        type: ActivityType.experience,
        status: ActivityStatus.completed,
        startTime: now.subtract(const Duration(days: 15)),
        endTime: now.subtract(const Duration(days: 14)),
        location: '雅韵茶舍',
        address: '北京市海淀区茶香路99号',
        maxParticipants: 20,
        currentParticipants: 20,
        price: 198.0,
        originalPrice: 298.0,
        images: [
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20Chinese%20tea%20ceremony%20elegant%20setup&image_size=landscape_4_3',
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=Chinese%20tea%20set%20and%20tea%20leaves&image_size=square',
        ],
        organizer: '雅韵茶舍',
        instructor: '陈茶师（高级茶艺师）',
        requirements: ['无特殊要求'],
        highlights: ['品尝名茶', '学习茶艺', '茶文化讲解'],
        createdAt: now.subtract(const Duration(days: 25)),
        updatedAt: now.subtract(const Duration(days: 14)),
        isFeatured: false,
        rating: 4.6,
        reviewCount: 67,
        tags: ['茶艺', '文化体验', '传统文化', '品茶'],
        category: '传统文化',
      ),
    ]);
  }

  /// 获取所有活动
  Future<List<Activity>> getAllActivities() async {
    await Future.delayed(const Duration(milliseconds: 500)); // 模拟网络延迟
    return List.from(_activities);
  }

  /// 根据筛选条件获取活动
  Future<List<Activity>> getActivitiesByFilter(ActivityFilter filter) async {
    await Future.delayed(const Duration(milliseconds: 300));
    
    switch (filter) {
      case ActivityFilter.all:
        return List.from(_activities);
      case ActivityFilter.upcoming:
        return _activities.where((a) => a.status == ActivityStatus.upcoming).toList();
      case ActivityFilter.ongoing:
        return _activities.where((a) => a.status == ActivityStatus.ongoing).toList();
      case ActivityFilter.completed:
        return _activities.where((a) => a.status == ActivityStatus.completed).toList();
      case ActivityFilter.workshop:
        return _activities.where((a) => a.type == ActivityType.workshop).toList();
      case ActivityFilter.course:
        return _activities.where((a) => a.type == ActivityType.course).toList();
      case ActivityFilter.performance:
        return _activities.where((a) => a.type == ActivityType.performance).toList();
      case ActivityFilter.experience:
        return _activities.where((a) => a.type == ActivityType.experience).toList();
      case ActivityFilter.exhibition:
        return _activities.where((a) => a.type == ActivityType.exhibition).toList();
      case ActivityFilter.featured:
        return _activities.where((a) => a.isFeatured).toList();
      case ActivityFilter.free:
        return _activities.where((a) => a.price == 0).toList();
      case ActivityFilter.paid:
        return _activities.where((a) => a.price > 0).toList();
    }
  }

  /// 获取热门活动
  Future<List<Activity>> getHotActivities({int limit = 5}) async {
    await Future.delayed(const Duration(milliseconds: 300));
    final hotActivities = List.from(_activities)
      ..sort((a, b) => (b.rating * b.reviewCount).compareTo(a.rating * a.reviewCount));
    return hotActivities.take(limit).toList();
  }

  /// 获取推荐活动
  Future<List<Activity>> getRecommendedActivities({int limit = 5}) async {
    await Future.delayed(const Duration(milliseconds: 300));
    final recommended = _activities.where((a) => 
      a.status == ActivityStatus.upcoming || a.status == ActivityStatus.ongoing
    ).toList()
      ..shuffle(Random());
    return recommended.take(limit).toList();
  }

  /// 获取精选活动
  Future<List<Activity>> getFeaturedActivities({int limit = 3}) async {
    await Future.delayed(const Duration(milliseconds: 300));
    return _activities.where((a) => a.isFeatured).take(limit).toList();
  }

  /// 根据ID获取活动详情
  Future<Activity?> getActivityById(String id) async {
    await Future.delayed(const Duration(milliseconds: 200));
    try {
      return _activities.firstWhere((a) => a.id == id);
    } catch (e) {
      return null;
    }
  }

  /// 搜索活动
  Future<List<Activity>> searchActivities(String query) async {
    await Future.delayed(const Duration(milliseconds: 400));
    if (query.isEmpty) return [];
    
    final lowerQuery = query.toLowerCase();
    return _activities.where((activity) {
      return activity.title.toLowerCase().contains(lowerQuery) ||
             activity.description.toLowerCase().contains(lowerQuery) ||
             activity.tags.any((tag) => tag.toLowerCase().contains(lowerQuery)) ||
             activity.category.toLowerCase().contains(lowerQuery);
    }).toList();
  }

  /// 报名活动
  Future<bool> registerForActivity(String activityId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 500));
    
    final activity = await getActivityById(activityId);
    if (activity == null || !activity.canRegister) {
      return false;
    }

    final registrationKey = '${userId}_$activityId';
    if (_userRegistrations.contains(registrationKey)) {
      return false; // 已经报名
    }

    // 更新活动参与人数
    final index = _activities.indexWhere((a) => a.id == activityId);
    if (index != -1) {
      _activities[index] = _activities[index].copyWith(
        currentParticipants: _activities[index].currentParticipants + 1,
      );
      _userRegistrations.add(registrationKey);
      return true;
    }
    
    return false;
  }

  /// 取消报名
  Future<bool> cancelRegistration(String activityId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 300));
    
    final registrationKey = '${userId}_$activityId';
    if (!_userRegistrations.contains(registrationKey)) {
      return false; // 未报名
    }

    // 更新活动参与人数
    final index = _activities.indexWhere((a) => a.id == activityId);
    if (index != -1) {
      _activities[index] = _activities[index].copyWith(
        currentParticipants: _activities[index].currentParticipants - 1,
      );
      _userRegistrations.remove(registrationKey);
      return true;
    }
    
    return false;
  }

  /// 检查用户是否已报名
  Future<bool> isUserRegistered(String activityId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 100));
    final registrationKey = '${userId}_$activityId';
    return _userRegistrations.contains(registrationKey);
  }

  /// 收藏活动
  Future<bool> favoriteActivity(String activityId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 200));
    final favoriteKey = '${userId}_$activityId';
    if (!_userFavorites.contains(favoriteKey)) {
      _userFavorites.add(favoriteKey);
      return true;
    }
    return false;
  }

  /// 取消收藏
  Future<bool> unfavoriteActivity(String activityId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 200));
    final favoriteKey = '${userId}_$activityId';
    return _userFavorites.remove(favoriteKey);
  }

  /// 检查用户是否已收藏
  Future<bool> isActivityFavorited(String activityId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 100));
    final favoriteKey = '${userId}_$activityId';
    return _userFavorites.contains(favoriteKey);
  }

  /// 获取用户收藏的活动
  Future<List<Activity>> getUserFavoriteActivities(String userId) async {
    await Future.delayed(const Duration(milliseconds: 300));
    final favoriteActivityIds = _userFavorites
        .where((key) => key.startsWith('${userId}_'))
        .map((key) => key.split('_')[1])
        .toList();
    
    return _activities.where((a) => favoriteActivityIds.contains(a.id)).toList();
  }

  /// 获取用户报名的活动
  Future<List<Activity>> getUserRegisteredActivities(String userId) async {
    await Future.delayed(const Duration(milliseconds: 300));
    final registeredActivityIds = _userRegistrations
        .where((key) => key.startsWith('${userId}_'))
        .map((key) => key.split('_')[1])
        .toList();
    
    return _activities.where((a) => registeredActivityIds.contains(a.id)).toList();
  }

  /// 获取活动统计信息
  Future<Map<String, int>> getActivityStats() async {
    await Future.delayed(const Duration(milliseconds: 200));
    return {
      'total': _activities.length,
      'upcoming': _activities.where((a) => a.status == ActivityStatus.upcoming).length,
      'ongoing': _activities.where((a) => a.status == ActivityStatus.ongoing).length,
      'completed': _activities.where((a) => a.status == ActivityStatus.completed).length,
      'featured': _activities.where((a) => a.isFeatured).length,
    };
  }

  /// 获取活动分类统计
  Future<Map<String, int>> getCategoryStats() async {
    await Future.delayed(const Duration(milliseconds: 200));
    final Map<String, int> stats = {};
    for (final activity in _activities) {
      stats[activity.category] = (stats[activity.category] ?? 0) + 1;
    }
    return stats;
  }

  /// 清除所有数据（用于测试）
  void clearAllData() {
    _activities.clear();
    _userRegistrations.clear();
    _userFavorites.clear();
  }
}